
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h> 


//根据端口号和IP地址  返回一个监听套接字
int create_socket(short port , char * ipstr)
{
    //创建一个套接字
    int sock = socket(AF_INET , SOCK_DGRAM , 0);
    if(sock == -1)
    {
        perror("socket error\n");
        return -1;
    }   
    return sock;

}


//./a.out prot ip
int main(int argc , char * argv[])
{
    int sock = create_socket( atoi(argv[1] ),argv[2]);
    if(sock == -1)
    {
        printf("create_socker error\n");
        return -1;
    }
    
    //指定对方的（UDP——Server的）网络地址 ：IP地址和端口号
    struct sockaddr_in Server; 
    Server.sin_family = AF_INET; //指定协议族 
    Server.sin_port = htons(atoi(argv[1]));//指定端口号 
    Server.sin_addr.s_addr = inet_addr(argv[2]);//指定IP地址

    socklen_t addrlen = sizeof(Server);

     //要发送的数据 
     unsigned char sendbuf[]={"hello UDP Server!"} ;
     unsigned char recvbuf[1024]={0} ;
     int ret = sendto(sock, sendbuf , strlen(sendbuf), 0 ,  (struct sockaddr *)&Server , addrlen  ); 
    if(ret == -1)
    {
        perror("sendto error\n");
        return -1;
    }

    ret = recvfrom(sock ,recvbuf, sizeof(recvbuf),0 , (struct sockaddr *)&Server , &addrlen  );
    if(ret > 0)
    {
        recvbuf[ret] = '\0';
        printf("recv data : %s\n",recvbuf);
    }

    close(sock);
   
}



















































